package com.gshrms.org.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gshrms.common.annotation.DataScope;
import com.gshrms.common.constant.UserConstants;
import com.gshrms.common.core.domain.entity.SysUser;
import com.gshrms.common.core.domain.model.LoginUser;
import com.gshrms.common.exception.org.OrgNotExistsException;
import com.gshrms.common.exception.org.OrgParentNotExistsException;
import com.gshrms.common.exception.org.OrgTaxNoExistsException;
import com.gshrms.common.utils.SecurityUtils;
import com.gshrms.org.domain.OrgInfo;
import com.gshrms.common.utils.DateUtils;
import com.gshrms.common.utils.StringUtils;
import com.gshrms.common.utils.spring.SpringUtils;
import com.gshrms.org.domain.OrgRoleStaff;
import com.gshrms.org.domain.dto.OrgRoleStaffJoinDto;
import com.gshrms.org.domain.params.OrgInfoForEditTaxNoParams;
import com.gshrms.org.domain.vo.OrgInfoTreeSelect;
import com.gshrms.org.mapper.OrgRoleStaffMapper;
import com.gshrms.system.mapper.SysUserMapper;
import com.gshrms.system.mapper.SysUserMenusMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gshrms.org.mapper.OrgInfoMapper;
import com.gshrms.org.service.IOrgInfoService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 组织Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-29
 */
@Service
public class OrgInfoServiceImpl extends ServiceImpl<OrgInfoMapper, OrgInfo> implements IOrgInfoService {
    @Autowired
    private OrgInfoMapper orgInfoMapper;
    @Autowired
    private OrgRoleStaffMapper orgRoleStaffMapper;

    @Autowired
    private SysUserMenusMapper sysUserMenusMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询组织
     *
     * @param orgId 组织主键
     * @return 组织
     */
    @Override
    public OrgInfo selectOrgInfoByOrgId(Long orgId) {
        return orgInfoMapper.selectOrgInfoByOrgId(orgId);
    }

    /**
     * 查询组织列表
     *
     * @param orgInfo 组织
     * @return 组织
     */
    @Override
    public List<OrgInfo> selectOrgInfoList(OrgInfo orgInfo) {
        List<OrgInfo> orgInfos = orgInfoMapper.selectOrgInfoList(orgInfo);
        return orgInfos;
    }


    /**
     * 查询组织列表
     *
     * @param orgInfo 组织
     * @return 组织
     */
    @Override
    public List<OrgInfo> selectOrgInfoAndRoleStaffList(OrgInfo orgInfo) {
        return orgInfoMapper.selectOrgInfoAndRoleStaffList(orgInfo);
    }




    /**
     * 查询组织树结构信息
     *
     * @param orgInfo 组织信息
     * @return 组织树信息集合
     */
    @Override
    public List<OrgInfoTreeSelect> selectOrgTreeList(OrgInfo orgInfo) {
        List<OrgInfo> orgInfos = this.selectOrgInfoList(orgInfo);
        return buildOrgTreeSelect(orgInfos);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param orgInfos 组织列表
     * @return 下拉树结构列表
     */
    @Override
    public List<OrgInfo> buildOrgTree(List<OrgInfo> orgInfos) {
        List<OrgInfo> returnList = new ArrayList<OrgInfo>();
        List<Long> tempList = orgInfos.stream().map(OrgInfo::getOrgId).collect(Collectors.toList());
        for (OrgInfo orgInfo : orgInfos) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(orgInfo.getParentId())) {
                recursionFn(orgInfos, orgInfo);
                returnList.add(orgInfo);
            }
        }
        if (returnList.isEmpty()) {
            returnList = orgInfos;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param orgInfos 组织列表
     * @return 下拉树结构列表
     */
    @Override
    public List<OrgInfoTreeSelect> buildOrgTreeSelect(List<OrgInfo> orgInfos) {
        List<OrgInfo> orgTrees = buildOrgTree(orgInfos);
        return orgTrees.stream().map(OrgInfoTreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 查询组织是否存在员工
     *
     * @param orgId 组织ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkOrgExistStaff(Long orgId) {
        int result = orgInfoMapper.checkOrgExistStaff(orgId);
        return result > 0;
    }

    /**
     * 查询是否存在子节点
     *
     * @param orgId 组织ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean hasChildByOrgId(Long orgId) {
        int result = orgInfoMapper.hasChildByOrgId(orgId);
        return result > 0;
    }

    /**
     * 查询是否存在正常状态的子组织
     *
     * @param orgId 组织ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenOrgById(Long orgId) {
        return orgInfoMapper.selectNormalChildrenOrgById(orgId);
    }

    /**
     * 根据祖级列表名称和组织名称，查询组织ID
     *
     * @param ancestorsName 祖级列表名称
     * @param orgName       组织名称
     * @return
     */
    @Override
    public Long selectOrgIdByAncestorsNamesAndOrgName(String ancestorsName, String orgName) {
        if (ancestorsName == null) ancestorsName = "";
        return orgInfoMapper.selectOrgIdByAncestorsNamesAndOrgName(ancestorsName, orgName);
    }


    /**
     * 校验组织好是否唯一
     *
     * @param orgInfo 组织
     * @return
     */
    @Override
    public boolean checkOrgNoUnique(OrgInfo orgInfo) {
        Long orgId = StringUtils.isNull(orgInfo.getOrgId()) ? -1L : orgInfo.getOrgId();

        OrgInfo info = orgInfoMapper.checkOrgNoUnique(orgInfo.getOrgNo());
        if (StringUtils.isNotNull(info) && info.getOrgId().longValue() != orgId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验组织名称在同一个父级下是否唯一
     *
     * @param orgName  组织名称
     * @param parentId 父组织ID
     * @param orgId    组织ID
     * @return
     */
    @Override
    public boolean checkOrgNameNoUnique(String orgName, Long parentId, Long orgId) {
        int result = orgInfoMapper.checkOrgNameNoUnique(orgName, parentId, orgId);
        if (result == 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增组织
     *
     * @param orgInfo 组织
     * @return 结果
     */
    @Override
    @Transactional
    public int insertOrgInfo(OrgInfo orgInfo) {
        // 获取父组织信息
        if (orgInfo.getParentId() == null || orgInfo.getParentId().equals(0L)) {
            orgInfo.setAncestors("0");
        } else {
            OrgInfo orgInfoParent = orgInfoMapper.selectOrgInfoByOrgId(orgInfo.getParentId());
            if (orgInfoParent == null) {
                throw new OrgParentNotExistsException();
            }
            String string = orgInfoParent.getAncestors() + "," + orgInfoParent.getOrgId();
            orgInfo.setAncestors(string);
            orgInfo.setAncestorsJson("["+string+"]");
        }

        orgInfo.setCreateTime(DateUtils.getNowDate());
        int result = orgInfoMapper.insertOrgInfo(orgInfo);

        // 更新组织角色
        this.batchOrgRoleStaff(orgInfo);

        return result;
    }

    /**
     * 修改组织
     *
     * @param orgInfo 组织
     * @return 结果
     */
    @Override
    public int updateOrgInfo(OrgInfo orgInfo) {
        orgInfo.setUpdateTime(DateUtils.getNowDate());
        int result = orgInfoMapper.updateOrgInfo(orgInfo);

        // 更新组织角色
        this.batchOrgRoleStaff(orgInfo);

        return result;
    }

    /**
     * 修改组织税号
     *
     * @param params 组织
     * @return 结果
     */
    public int updateOrgInfoForTaxNo(OrgInfoForEditTaxNoParams params) {
        // 获取当前组织
        OrgInfo orgInfo = orgInfoMapper.selectOrgInfoByOrgId(params.getOrgId());
        if (orgInfo == null) {
            throw new OrgNotExistsException();
        }

        // 检查税号是否重复
        OrgInfo checkOrgInfo = orgInfoMapper.checkOrgNoUnique(params.getTaxNo());
        if (checkOrgInfo != null && !checkOrgInfo.getOrgId().equals(orgInfo.getOrgId())) {
            throw new OrgTaxNoExistsException();
        }

        // 修改税号
        orgInfo.setOrgNo(params.getTaxNo());
        orgInfo.setTaxNo(params.getTaxNo());
        orgInfo.setUpdateTime(DateUtils.getNowDate());
        return orgInfoMapper.updateOrgInfo(orgInfo);
    }

    /**
     * 删除组织信息
     *
     * @param orgId 组织主键
     * @return 结果
     */
    @Override
    public int deleteOrgInfoByOrgId(Long orgId) {
        return orgInfoMapper.deleteOrgInfoByOrgId(orgId);
    }

    /**
     * 删除组织信息
     *
     * @param orgIds 组织主键
     * @return 结果
     */
    @Override
    public int deleteOrgInfoByOrgIds(Long[] orgIds) {
        return orgInfoMapper.deleteOrgInfoByOrgIds(orgIds);
    }






    /**
     * 更新组织角色
     *
     * @param orgInfo
     */
    private void batchOrgRoleStaff(OrgInfo orgInfo) {
        // 删除角色
        orgRoleStaffMapper.deleteOrgRoleStaffByOrgId(orgInfo.getOrgId());

        Long orgId = orgInfo.getOrgId();
        List<OrgRoleStaffJoinDto> orgRoleStaffJoinDtoList = orgInfo.getOrgRoleStaffJoin();
        if (orgRoleStaffJoinDtoList != null) {
            List<OrgRoleStaff> orgRoleStaffList = new ArrayList<>();
            for (OrgRoleStaffJoinDto orgRoleStaffJoinDto : orgRoleStaffJoinDtoList) {
                Long roleId = orgRoleStaffJoinDto.getRoleId();
                String staffIds = orgRoleStaffJoinDto.getStaffIds();
                if (StringUtils.isBlank(staffIds)) continue;

                String[] staffIdArr = staffIds.split(",");
                for (String staffId : staffIdArr) {
                    OrgRoleStaff orgRoleStaff = new OrgRoleStaff();
                    orgRoleStaff.setOrgId(orgId);
                    orgRoleStaff.setRoleId(roleId);
                    orgRoleStaff.setStaffId(Long.parseLong(staffId));
                    orgRoleStaffList.add(orgRoleStaff);
                }
            }
            if (!orgRoleStaffList.isEmpty()) orgRoleStaffMapper.batchOrgRoleStaff(orgRoleStaffList);
        }
    }


    /**
     * 递归列表
     */
    private void recursionFn(List<OrgInfo> list, OrgInfo t) {
        // 得到子节点列表
        List<OrgInfo> childList = getChildList(list, t);
        t.setChildren(childList);
        for (OrgInfo tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<OrgInfo> getChildList(List<OrgInfo> list, OrgInfo t) {
        List<OrgInfo> tlist = new ArrayList<OrgInfo>();
        Iterator<OrgInfo> it = list.iterator();
        while (it.hasNext()) {
            OrgInfo n = (OrgInfo) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getOrgId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<OrgInfo> list, OrgInfo t) {
        return getChildList(list, t).size() > 0;
    }

}
